import { useAccountLoginApi, useUserInfoApi, useLogoutApi, useUpdateInfoApi, useEmailLoginApi, useBindEmailApi } from "@/api/user/user";
import { useCampusCheckApi } from "@/api/user/campus";
import { useSessionStorage } from "@vueuse/core";
import { defineStore } from "pinia";

export const useUserStore = defineStore("useUserStore", {
  state: () => ({
    user: {
      userId: "",
      userName: "",
      userPhoto: "",
      userAccount: "",
      collegeId: "",
      email: "",
      userPhone: "",
      userRole: 0,
      createTime: "",
    },
    campus: {
      campusId: "",
      collegeName: "",
      studentNumber: "",
      realName: "",
    },
    token: sessionStorage.getItem("accessToken"),
  }),
  actions: {
    setUser(val: any) {
      this.user = val;
    },
    setToken(val: any) {
      this.token = val;
      sessionStorage.setItem("accessToken", val);
    },
    setCampus(val: any) {
      this.campus = val;
    },
    // 账号登录
    async accountLoginAction(loginForm: any) {
      const { data } = await useAccountLoginApi(loginForm);
      this.setToken(data.accessToken);
    },
    // 邮箱登录
    async emailLoginAction(emailForm: any) {
      const { data } = await useEmailLoginApi(emailForm);
      this.setToken(data.accessToken);
    },
    // 绑定邮箱
    async bindEmailAction(emailForm: any) {
      await useBindEmailApi(emailForm);
      this.user.email = emailForm.userEmail
      this.getUserInfoAction()
    },
    // 获取用户信息
    async getUserInfoAction() {
      const { data } = await useUserInfoApi();
      this.setUser(data);
    },
    // 修改用户信息
    async updateInfoAction(userForm: any) {
      await useUpdateInfoApi(userForm);
      this.user.userName = userForm.userName
      this.user.userPhoto = userForm.userPhoto
      this.getUserInfoAction()
    },
    // 用户校园认证信息
    async campusCheckAction(campusForm: any) {
      await useCampusCheckApi(campusForm)
      this.user.userRole = 2
      this.getUserInfoAction()
    },
    // 用户退出登录
    async logoutAction() {
      await useLogoutApi();
      this.setToken(null)
      this.setUser({})
      sessionStorage.removeItem("accessToken")
    },
  },
});
